<template>
  <div id="design" ref="design" class="design" @mousedown="handleMouseDown">
    <!-- 网格线 -->
    <Grid />
    <!-- 组件区域 -->
    <DesignShape
      ref="shape"
      v-for="(item, index) in complexList"
      :key="index"
      :element="item"
      :zoom="zoom"
      @handleContext="handleContext"
      @dblclickContext="doubleContext"
    >
      <component
        :is="item.name"
        :complex="item"
        :config="item.config"
        :count="item.count"
        :zoom="zoom"
      />
    </DesignShape>
    <!-- 选框 -->
    <SelectFrame :status="isFraming" :config="frame" />
  </div>
</template>

<script>
import Grid from "./components/Grid";
import DesignShape from "./components/DesignShape";
import SelectFrame from "./components/SelectFrame";
export default {
  components: {
    DesignShape,
    Grid,
    SelectFrame,
  },
  props: {
    zoom: Number,
    complexItem: {
      typeof: Object,
    },
    complexList: {
      type: Array,
    },
  },
  data() {
    return {
      isEdit: true,
      isFraming: false,
      isSpace: false,
      frame: {
        clientX: 0,
        clientY: 0,
        opacity: 0,
        x: 0,
        y: 0,
        w: 0,
        h: 0,
      },
      // 右键菜单
      contextMenu: {
        show: false,
        left: 0,
        top: 0,
        z: 1024,
      },
    };
  },
  //   created() {
  //     window.addEventListener("keyup", this.keyUp);
  //     window.addEventListener("keydown", this.keyDown);
  //   },
  //   beforeDestroy() {
  //     // 在组件生命周期结束的时候销毁。
  //     window.removeEventListener("keyup", this.keyUp, false);
  //     window.removeEventListener("keydown", this.keyDown, false);
  //   },
  methods: {
    //监听键盘事件
    keyDown() {
      document.onkeydown = (e) => {
        //事件对象兼容
        let el = e || window.event;
        var keyCode = el.keyCode || el.which;
        //关闭浏览器快捷键
        window.event.preventDefault();
        // console.log(keyCode, el.ctrlKey);
        if (keyCode == 32) {
          this.isSpace = true;
          console.log("空格");
        }
      };
    },
    keyUp() {
      document.onkeyup = (e) => {
        //事件对象兼容
        let el = e || window.event;
        var keyCode = el.keyCode || el.which;
        console.log(keyCode, "键盘抬起");
      };
    },
    doubleContext(data) {
      console.log("双击组件事件", data);
      if (data.config.type === "table") {
        this.$parent.sourceDialog = true;
      }
    },
    // 组件点击事件
    handleContext(data) {
      this.sendAttr(data);
      this.$store.dispatch("design/settingMenu", {
        show: false,
        top: 0,
        left: 0,
      });
      this.complexList
        .map((item) => {
          item.focused = false;
          return item;
        })
        .filter((item) => item === data)
        .forEach((item) => {
          item.focused = true;
        });
    },
    // 通过version更新组件的配置属性
    sendAttr(data) {
      // console.log(item, "设置配置项");
      const complexList = require.context(
        "@/library/components",
        true,
        /.vue$/
      ); //获取自定义组件
      complexList.keys().forEach((fileName) => {
        const component = complexList(fileName).default; // 组件
        const componentName = component.pageData
          ? component.pageData.name
          : null;
        if (componentName && componentName == data.name) {
          if (data.version != component.pageData.version) {
            data.version = component.pageData.version;
            if (data.config.attr) {
              data.config.attr = this.filterAttrNews(
                data.config.attr,
                component.pageData.config.attr
              );
              console.log(data.config.attr);
            }
          }
        }
      });
      // this.complexList
      //   .map((item) => {
      //     item.focused = false;
      //     return item;
      //   })
      //   .filter((item) => item === data)
      //   .forEach((item) => {
      //     item.focused = true;
      //   });
    },
    // 检查组件属性是否和本地组件属性同步
    filterAttrNews(attr, verifyAttr) {
      let list = JSON.parse(JSON.stringify(attr));
      let dete = [];
      let add = [];
      // 查询出已删除属性
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        const findIndex = verifyAttr.findIndex((data) => {
          return data.key === element.key;
        });
        if (findIndex <= -1) {
          list.splice(index, 1);
          index--;
        }
      }
      // 查询出新增属性
      verifyAttr.map((item, index) => {
        const findItem = list.find((data) => {
          return data.key === item.key;
        });
        if (!findItem) {
          list.splice(index, 0, item);
        }
      });
      return list;
    },
    // 鼠标按下事件
    handleMouseDown(e) {
      if (!this.complexItem) {
        e.preventDefault();
      }

      this.$store.dispatch("design/settingMenu", {
        show: false,
        top: 0,
        left: 0,
      });
      // 按下鼠标记录选框的起始点 初始化选框
      this.frame.x = e.offsetX;
      this.frame.y = e.offsetY;
      this.frame.clientX = e.clientX;
      this.frame.clientY = e.clientY;
      this.isFraming = true;
      this.clearWeightFocused();

      var that = this;
      const move = (moveEvent) => {
        // 绘制选择框
        if (this.isFraming) {
          this.setFrameArea(moveEvent);
        }
      };

      const up = () => {
        document.removeEventListener("mousemove", move);
        document.removeEventListener("mouseup", up);
        that.stopFrameArea();
      };

      document.addEventListener("mousemove", move);
      document.addEventListener("mouseup", up);
    },
    // 清空选择区域
    stopFrameArea() {
      this.isFraming = false;
      this.frame.w = 0;
      this.frame.h = 0;
    },
    // 绘制矩形选框
    setFrameArea(e) {
      let screenTop = document
        .getElementById("design")
        .getBoundingClientRect().top;
      let screenLeft = document
        .getElementById("design")
        .getBoundingClientRect().left;
      if (e.clientX > this.frame.clientX && e.clientY > this.frame.clientY) {
        // 右下
        this.frame.w = (e.clientX - this.frame.clientX) / this.zoom;
        this.frame.h = (e.clientY - this.frame.clientY) / this.zoom;
      }
      this.setWeightFocused();
    },
    // 清空选中的组件
    clearWeightFocused() {
      this.complexList.map((item) => {
        item.focused = false;
        return item;
      });
    },
    // 更改组件的选中状态
    setWeightFocused() {
      this.complexList
        .map((item) => {
          item.focused = false;
          return item;
        })
        .filter(this.isFramingWeight)
        .forEach((item) => {
          item.focused = true;
        });
    },
    // 组件是否被选中
    isFramingWeight(item) {
      return !(
        item.x > this.frame.x + this.frame.w ||
        item.y > this.frame.y + this.frame.h ||
        this.frame.x > item.x + item.w ||
        this.frame.y > item.y + item.h
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.design {
  position: relative;
  width: 100%;
  height: 100%;

  .lock {
    opacity: 0.5;

    &:hover {
      cursor: not-allowed;
    }
  }
}
</style>
